/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.z100h.supplychain.purchase.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.rribbit.RequestResponseBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.RRBHints;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.z100h.supplychain.evidence.entity.Stockout;
import com.z100h.supplychain.evidence.entity.WarehouseReceipt;
import com.z100h.supplychain.evidence.facade.WarehousingFacade;
import com.z100h.supplychain.purchase.entity.PurchaseOrder;
import com.z100h.supplychain.purchase.entity.PurchaseOrderItemErpInfo;
import com.z100h.supplychain.purchase.entity.PurchaseOrderItemVo;
import com.z100h.supplychain.purchase.service.PurchaseOrderItemService;
import com.z100h.supplychain.purchase.service.PurchaseOrderService;
import com.z100h.supplychain.sku.entity.Sku;
import com.z100h.supplychain.sku.service.SkuService;
import com.z100h.supplychain.supplier.entity.Contract;
import com.z100h.supplychain.supplier.entity.Supplier;
import com.z100h.supplychain.supplier.service.ContractService;
import com.z100h.supplychain.supplier.service.SupplierService;

/**
 * 供应链采购单Controller
 * @author madara
 * @version 2018-09-20
 */
@Controller
@RequestMapping(value = "${adminPath}/purchase/purchaseOrder")
public class PurchaseOrderController extends BaseController {

	@Autowired
	private PurchaseOrderService purchaseOrderService;

	@Autowired
	private SupplierService supplierService;

	@Autowired
	private ContractService contractService;

	@Autowired
	private SkuService skuService;

	@Autowired
	private PurchaseOrderItemService purchaseOrderItemService;

	@Autowired
	private WarehousingFacade<WarehouseReceipt> warehousingFacade;

	@Autowired
	private RequestResponseBus rrb;

	@ModelAttribute
	public PurchaseOrder get(@RequestParam(required = false) String id) {
		PurchaseOrder entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = purchaseOrderService.get(id);
		}
		if (entity == null) {
			entity = new PurchaseOrder();
		}
		return entity;
	}

	/**
	 * 供应链采购单列表页面
	 */
	@RequiresPermissions("purchase:purchaseOrder:list")
	@RequestMapping(value = { "list", "" })
	public String list() {
		return "supplychain/purchase/purchaseOrderList";
	}

	/**
	* 供应链采购单列表数据
	*/
	@ResponseBody
	@RequiresPermissions("purchase:purchaseOrder:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(PurchaseOrder purchaseOrder, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<PurchaseOrder> page = purchaseOrderService.findPage(new Page<PurchaseOrder>(request, response),
				purchaseOrder);
		return getBootstrapData(page);
	}

	/**
	 * 添加采购单
	 * @param purchaseOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions(value = { "purchase:purchaseOrder:view", "purchase:purchaseOrder:add",
			"purchase:purchaseOrder:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form")
	public String form(HttpServletRequest request, PurchaseOrder purchaseOrder, Model model) {
		model.addAttribute("purchaseOrder", purchaseOrder);
		if (StringUtils.isBlank(purchaseOrder.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}

		// 修改方法
		if (null != purchaseOrder.getId()) {

		}

		User logUser = UserUtils.getUser();
		Supplier supplier = new Supplier();
		supplier.setCompanyId(logUser.getCompany().getId());
		List<Supplier> supplierList = supplierService.findList(supplier);

		request.setAttribute("supplierList", supplierList);
		Contract contract = new Contract();
		contract.setCompanyId(logUser.getCompany().getId());
		List<Contract> contractList = contractService.findList(contract);

		request.setAttribute("contractList", contractList);

		// 查询同仓库下的sku
		Sku sku = new Sku();
		sku.setDepartmentId(UserUtils.getUser().getOffice().getId());
		List<Sku> skuList = skuService.findList(sku);
		request.setAttribute("skuList", skuList);

		return "supplychain/purchase/add_purchase";
	}

	/**
	 * 保存供应链采购单
	 */
	@RequestMapping(value = "savePurchaseOrder")
	@ResponseBody
	public Map<String, Object> savePurchaseOrder(HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		// 新增或编辑表单保存
		try {
			String jsons = request.getParameter("jsons");
			StringEscapeUtils.escapeHtml4(jsons);
			json = JSON.parseObject(jsons);
			purchaseOrderService.savePurchaseOrder(json);// 保存
			map.put("message", 1);
		} catch (Exception e) {
			logger.error("Controller  PurchaseOrderController  savePurchaseOrder.", e);
			map.put("message", 0);
		}

		return map;
	}

	/**
	 * 采购单置为完成状态
	 * 并生成入库单
	 * 
	 * @param request
	 * @param model
	 * @param redirectAttributes
	 * @return
	 * @throws Exception
	 * @author: Elvin Zhao - 279152260@qq.com 
	 * @date: Created on 2019年9月17日 下午7:00:42
	 */
	@RequestMapping(value = "finishPurchaseOrderAndCreateWarehouseReceipt")
	@ResponseBody
	public Map<String, Object> finishPurchaseOrderAndCreateWarehouseReceipt(HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String purchaseOrderId = request.getParameter("purchaseOrderId");
			purchaseOrderService.createWarehouseReceipt(purchaseOrderId, true);
			map.put("message", 1);
		} catch (Exception e) {
			logger.error("Controller  PurchaseOrderController  savePurchaseOrder.", e);
			map.put("message", 0);
		}

		return map;
	}

	/**
	 * 
	 * 微信采购单完成
	 * 
	 * @param request
	 * @param purchaseOrderId
	 * @return
	 * @throws Throwable
	 * @author: Fyh - 1009173473@qq.com 
	 * @date: Created on 2020年5月7日 上午10:48:11
	 */
	@ResponseBody
	@RequestMapping(value = "mp/finish")
	public AjaxJson mpFinish(HttpServletRequest request, String purchaseOrderId, Boolean ignore) throws Throwable {
		AjaxJson respBody = new AjaxJson();
		try {
			if (localLogin(request)) {

				String evidenceId = purchaseOrderService.createWarehouseReceipt(purchaseOrderId, ignore);
				// 直接入库质检完成
				WarehouseReceipt warehouseReceipt = new WarehouseReceipt(evidenceId);
				warehouseReceipt.setJsons(null);
				warehousingFacade.saveAndQc(warehouseReceipt);

				/**
				 * 写日报,标准采购单入口写
				 */
				PurchaseOrder purchaseOrder = purchaseOrderService.get(purchaseOrderId);
				if (purchaseOrder != null && StringUtils.equals(purchaseOrder.getType(), "STANDARD")
						&& purchaseOrder.getCreateBy() != null
						&& StringUtils.isNotBlank(purchaseOrder.getCreateBy().getNo())) {
					rrb.send(RRBHints.ACCOUNT.SAVE_WORK_REPORT, purchaseOrder.getCreateBy().getNo(),
							StringUtils.join("[已入库采购单] ", purchaseOrder.getSupplierName(),
									" SKU" + purchaseOrder.getTotalPlant() + "个 ",
									purchaseOrder.getTotalPrice()));
				}
			}
		} catch (Throwable e) {
			respBody.setSuccess(false);
			respBody.setMsg("采购单完成异常：" + e.getMessage());
			logger.error("mp/finish is error.", e);
		}
		return respBody;
	}

	@RequestMapping(value = "savePurchaseOrderAndWarehouseReceipt")
	@ResponseBody
	public Map<String, Object> savePurchaseOrderAndWarehouseReceipt(HttpServletRequest request, Model model,
			RedirectAttributes redirectAttributes) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject json = new JSONObject();
		// 新增或编辑表单保存
		try {
			String jsons = request.getParameter("jsons");
			StringEscapeUtils.escapeHtml4(jsons);
			json = JSON.parseObject(jsons);
			String warehouseId = request.getParameter("warehouseId");
			WarehouseReceipt warehouseReceipt = purchaseOrderService.savePurchaseOrderAndCreateWareReceipt(json);
			warehouseReceipt.setWarehouseId(warehouseId);
			warehousingFacade.batchSave(warehouseReceipt);
			map.put("message", 1);
		} catch (Throwable e) {
			logger.error("Controller  PurchaseOrderController  savePurchaseOrder.", e);
			map.put("message", 0);
		}

		return map;
	}

	/**
	 * 删除供应链采购单
	 */
	@ResponseBody
	@RequiresPermissions("purchase:purchaseOrder:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(PurchaseOrder purchaseOrder, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		purchaseOrderService.delete(purchaseOrder);
		j.setMsg("删除供应链采购单成功");
		return j;
	}

	/**
	 * 修改采购单
	 * @param purchaseOrder
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("purchase:purchaseOrder:updatePurchaseOrder")
	@RequestMapping(value = "updatePurchaseOrder")
	public String updatePurchaseOrder(PurchaseOrder purchaseOrder, HttpServletRequest request,
			HttpServletResponse response) {

		User logUser = UserUtils.getUser();
		Supplier supplier = new Supplier();
		supplier.setCompanyId(logUser.getCompany().getId());
		List<Supplier> supplierList = supplierService.findList(supplier);

		request.setAttribute("supplierList", supplierList);
		Contract contract = new Contract();
		contract.setCompanyId(logUser.getCompany().getId());
		List<Contract> contractList = contractService.findList(contract);

		request.setAttribute("contractList", contractList);

		// // 查询同仓库下的sku
		// Sku sku = new Sku();
		// sku.setDepartmentId(UserUtils.getUser().getOffice().getId());
		// List<Sku> skuList = skuService.findList(sku);
		// request.setAttribute("skuList", skuList);
		//
		// // 查询采购单明细
		// PurchaseOrderItem purchaseOrderItem = new PurchaseOrderItem();
		// purchaseOrderItem.setPurchaseOrderId(purchaseOrder.getId());
		// List<PurchaseOrderItem> itemList = purchaseOrderItemService.findList(purchaseOrderItem);
		// request.setAttribute("itemList", itemList);

		// 采购单主表信息
		PurchaseOrder purchaseOrderVo = purchaseOrderService.get(purchaseOrder.getId());
		request.setAttribute("purOrder", purchaseOrderVo);

		request.setAttribute("purchaseOrderId", purchaseOrder.getId());
		return "supplychain/purchase/update_purchase";
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("purchase:purchaseOrder:export")
	@RequestMapping(value = "export", method = RequestMethod.POST)
	public AjaxJson exportFile(PurchaseOrder purchaseOrder, HttpServletRequest request, HttpServletResponse response,
			RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
			String fileName = "供应链采购单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
			Page<PurchaseOrder> page = purchaseOrderService.findPage(new Page<PurchaseOrder>(request, response, -1),
					purchaseOrder);
			new ExportExcel("供应链采购单", PurchaseOrder.class).setDataList(page.getList()).write(response, fileName)
					.dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出供应链采购单记录失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 导入Excel数据
	
	 */
	@RequiresPermissions("purchase:purchaseOrder:import")
	@RequestMapping(value = "import", method = RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<PurchaseOrder> list = ei.getDataList(PurchaseOrder.class);
			for (PurchaseOrder purchaseOrder : list) {
				try {
					purchaseOrderService.save(purchaseOrder);
					successNum++;
				} catch (ConstraintViolationException ex) {
					failureNum++;
				} catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum > 0) {
				failureMsg.insert(0, "，失败 " + failureNum + " 条供应链采购单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 " + successNum + " 条供应链采购单记录" + failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入供应链采购单失败！失败信息：" + e.getMessage());
		}
		return "redirect:" + Global.getAdminPath() + "/purchase/purchaseOrder/?repage";
	}

	/**
	 * 采购单明细
	 * @param purchaseOrder
	 * @param request
	 * @param response
	 * @return
	 */
	@RequiresPermissions("purchase:purchaseOrder:detail")
	@RequestMapping(value = "detail")
	public String detail(PurchaseOrder purchaseOrder, HttpServletRequest request, HttpServletResponse response) {

		User logUser = UserUtils.getUser();
		Supplier supplier = new Supplier();
		supplier.setCompanyId(logUser.getCompany().getId());
		List<Supplier> supplierList = supplierService.findList(supplier);

		request.setAttribute("supplierList", supplierList);
		Contract contract = new Contract();
		contract.setCompanyId(logUser.getCompany().getId());
		List<Contract> contractList = contractService.findList(contract);

		request.setAttribute("contractList", contractList);

		// // 查询同仓库下的sku
		// Sku sku = new Sku();
		// // sku.setDepartmentId(UserUtils.getUser().getOffice().getId());
		// List<Sku> skuList = skuService.findList(sku);
		// request.setAttribute("skuList", skuList);
		//
		// // 查询采购单明细
		// PurchaseOrderItem purchaseOrderItem = new PurchaseOrderItem();
		// purchaseOrderItem.setPurchaseOrderId(purchaseOrder.getId());
		// List<PurchaseOrderItem> itemList = purchaseOrderItemService.findList(purchaseOrderItem);
		// request.setAttribute("itemList", itemList);

		// 采购单主表信息
		PurchaseOrder purchaseOrderVo = purchaseOrderService.get(purchaseOrder.getId());
		request.setAttribute("purOrder", purchaseOrderVo);
		request.setAttribute("purchaseOrderId", purchaseOrder.getId());
		System.out.println(purchaseOrder.getId());
		return "supplychain/purchase/detail";
	}

	@RequestMapping(value = "findPurchaseOrderDetail")
	@ResponseBody
	public List<PurchaseOrderItemVo> findPurchaseOrderDetail(String purchaseOrderId) {
		List<PurchaseOrderItemVo> purchaseOrderItemVoList = purchaseOrderItemService
				.findPurchaseOrderItemList(purchaseOrderId);
		return purchaseOrderItemVoList;

	}

	@ResponseBody
	@RequestMapping(value = "erpInfo")
	public AjaxJson erpInfo(String skuId) {
		AjaxJson j = new AjaxJson();
		try {
			User logUser = UserUtils.getUser();
			List<PurchaseOrderItemErpInfo> list = purchaseOrderService.findErpInfoBySkuId(skuId,
					logUser.getCompany().getId());
			j.put("erpInfo", list);
			j.setSuccess(true);
			j.setMsg("成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("失败！失败信息：" + e.getMessage());
		}
		return j;
	}

	/**
	 * 添加采购单2-修改的页面
	 * @param purchaseOrder
	 * @param model
	 * @return
	 */
	@RequiresPermissions(value = { "purchase:purchaseOrder:view", "purchase:purchaseOrder:add",
			"purchase:purchaseOrder:edit" }, logical = Logical.OR)
	@RequestMapping(value = "form2")
	public String form2(HttpServletRequest request, PurchaseOrder purchaseOrder, Model model) {
		model.addAttribute("purchaseOrder", purchaseOrder);
		if (StringUtils.isBlank(purchaseOrder.getId())) {// 如果ID是空为添加
			model.addAttribute("isAdd", true);
		}

		// 修改方法
		if (null != purchaseOrder.getId()) {

		}

		User logUser = UserUtils.getUser();
		Supplier supplier = new Supplier();
		supplier.setCompanyId(logUser.getCompany().getId());
		List<Supplier> supplierList = supplierService.findList(supplier);

		request.setAttribute("supplierList", supplierList);
		Contract contract = new Contract();
		contract.setCompanyId(logUser.getCompany().getId());
		List<Contract> contractList = contractService.findList(contract);

		request.setAttribute("contractList", contractList);

		// 查询同仓库下的sku
		Sku sku = new Sku();
		sku.setDepartmentId(UserUtils.getUser().getOffice().getId());
		List<Sku> skuList = skuService.findList(sku);
		request.setAttribute("skuList", skuList);

		return "supplychain/purchase/add_purchase2";
	}

	@RequestMapping(value = "purchaseDetail")
	public String purchaseDetail(String skuId, HttpServletRequest request) {
		request.setAttribute("id", skuId);
		return "supplychain/purchase/purchase_detail";
	}
}